package com.simdo.g768.SQL;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.simdo.g768.Bean.ArfcnPciBean;
import com.simdo.g768.Bean.HistoryBean;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.DateUtil;
import com.simdo.g768.Util.GsonUtil;
import com.simdo.g768.ZApplication;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@SuppressLint("Range")
public class DbManage {

    protected static DbManage _instance;
    private final SQLiteDatabase db;

    public DbManage(Context context) {
        db = new DbHelper(context).getWritableDatabase();
    }

    public static DbManage getInstance(Context context) {
        if (_instance == null) _instance = new DbManage(context);
        return _instance;
    }

    public SQLiteDatabase getDb() {
        return db;
    }


    /**
     * 功能           往表中添加数据
     *
     * @param bean   HistoryBean
     */
    public void addHistoryData(HistoryBean bean) {
        String config = GsonUtil.mapToJson(bean.getTraceConfigMap());
        db.execSQL("insert into history_tb(checked,mode,createTime,startTime,config) values(?,?,?,?,?)",
                new Object[]{bean.isChecked() ? 1 : 0, bean.getMode(), bean.getCreateTime(), bean.getStartTime(), config});
    }

    /**
     * 查询所有数据
     */
    public List<HistoryBean> getHistoryData() {
        List<HistoryBean> historyBeans = new ArrayList<>();

        Cursor cursor = select(DbHelper.HISTORY_TB);
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd hh:mm:ss");

        long nowTime = 0;
        try {
            String format = DateUtil.getMMddTime();
            nowTime = formatter.parse(format).getTime();
        } catch (ParseException e) {
            AppLog.E("getHistoryData formatter nowTime err = " + e.getMessage());
        }
        while (cursor.moveToNext()) {
            boolean checked = cursor.getInt(cursor.getColumnIndex("checked")) == 1;
            int mode = cursor.getInt(cursor.getColumnIndex("mode"));
            if (mode > 3 && ZApplication.getInstance().isTrace) continue;
            long createTime = cursor.getLong(cursor.getColumnIndex("createTime"));
            if (mode < 4 && nowTime - createTime > 86400000){
                AppLog.D("getHistoryData delete item, createTime = " + createTime);
                deleteData(createTime);
                continue;
            }
            String startTime = cursor.getString(cursor.getColumnIndex("startTime"));
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String config = cursor.getString(cursor.getColumnIndex("config"));

            HistoryBean bean = new HistoryBean(mode, GsonUtil.jsonToMap(config));
            if (bean.getImsi().length() < 15 && ZApplication.getInstance().isTrace) continue;
            bean.setChecked(checked);
            bean.setCreateTime(createTime);
            bean.setStartTime(startTime);
            bean.setName(name == null ? "" : name);
            historyBeans.add(bean);
        }
        cursor.close();

        return historyBeans;
    }

    /**
     * 更新最新时间
     */
    public void updateStartTime(HistoryBean bean) {
        db.execSQL("update " + DbHelper.HISTORY_TB + " set startTime = ? where createTime = ?", new String[]{bean.getStartTime(), String.valueOf(bean.getCreateTime())});
    }

    /**
     * 更新选择项
     */
    public void updateCheck(HistoryBean bean) {
        Log.e("updateCheck", "checked = " + bean.isChecked() + ", mode = " + bean.getMode());
        db.execSQL("update " + DbHelper.HISTORY_TB + " set checked = ? where createTime == ?", new Object[]{bean.isChecked() ? 1 : 0, bean.getCreateTime()});
    }

    /**
     * 更新目标
     */
    public void updateConfig(HistoryBean bean) {
        String config = GsonUtil.mapToJson(bean.getTraceConfigMap());
        db.execSQL("update " + DbHelper.HISTORY_TB + " set config = ? where createTime == ?", new String[]{config, String.valueOf(bean.getCreateTime())});
    }

    /**
     * 更新名称
     */
    public void updateName(HistoryBean bean) {
        db.execSQL("update " + DbHelper.HISTORY_TB + " set name = ? where createTime == ?", new String[]{bean.getName(), String.valueOf(bean.getCreateTime())});
    }

    /**
     * 删除数据
     */
    public void deleteData(HistoryBean bean) {
        db.execSQL("delete from " + DbHelper.HISTORY_TB + " where createTime == ?", new String[]{String.valueOf(bean.getCreateTime())});
    }
    public void deleteData(long createTime) {
        db.execSQL("delete from " + DbHelper.HISTORY_TB + " where createTime == ?", new String[]{String.valueOf(createTime)});
    }

    /**
     * 功能   获取该数据表的总行数
     */
    public long getDataCount(String tableName) {
        Cursor cursor = db.rawQuery("select count(*) from " + tableName, null);
        cursor.moveToFirst();
        long count = cursor.getLong(0);
        cursor.close();
        return count;
    }

    /**
     * 功能                 定位起查询num条数据
     *
     * @param tableName 表名
     * @param num       查询条数
     * @param start     从哪一行开始往后查
     * @return 返回包含结果的 Cursor
     */
    public Cursor select(String tableName, int start, int num) {
        return db.rawQuery("select * from " + tableName + " limit ? offset ?", new String[]{String.valueOf(num), String.valueOf(start)});
    }

    /**
     * 功能   降序查询数据表
     */
    public Cursor select(String tableName) {
        return db.rawQuery("select * from " + tableName + " order by _id desc", null);
    }

    /**
     * 功能          降序查询num条数据
     *
     * @param num 要查询的条数
     */
    public Cursor select(String tableName, int num) {
        return db.rawQuery("select * from " + tableName + " order by _id desc limit " + num, null);
    }

}

